<?php

namespace App\Admin\Controllers\Core;

use Dcat\Admin\Http\Controllers\AuthController as BaseAuthController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Symfony\Component\HttpFoundation\Response;

class AuthController extends BaseAuthController
{
    protected string $view = 'admin.login';

    public function postLogin(Request $request): Response
    {
        $credentials = $request->only([$this->username(), 'password', 'verify']);
        $remember = (bool) $request->input('remember', false);

        $validator = Validator::make($credentials, [
            $this->username() => 'required',
            'password' => 'required',
            'verify' => [
                config('admin.enable_captcha') ? 'required' : 'nullable',
                'captcha',
            ],
        ], [
            'verify.required' => '验证码必须填写',
            'verify.captcha' => '验证码不正确',
        ]);

        if ($validator->fails()) {
            return $this->validationErrorsResponse($validator);
        }

        unset($credentials['verify']);
        if ($this->guard()->attempt($credentials, $remember)) {
            return $this->sendLoginResponse($request);
        }

        return $this->validationErrorsResponse([
            $this->username() => $this->getFailedLoginMessage(),
        ]);
    }
}
